package com.media.publish;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.opengl.GLSurfaceView;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.baselibrary.MessageBus;
import com.baselibrary.activity.BaseActivity;
import com.baselibrary.manager.DialogManager;
import com.baselibrary.manager.LoadingManager;
import com.baselibrary.utils.DoubleUtils;
import com.baselibrary.utils.EventBusUtils;
import com.baselibrary.utils.FileUtils;
import com.baselibrary.utils.KeyBoardUtils;
import com.baselibrary.utils.StorageUtils;
import com.baselibrary.utils.ToastUtils;
import com.media.R;
import com.media.publish.adapter.FilterItemAdapter;
import com.media.publish.bean.EditVideoAttributeBean;
import com.media.publish.utils.Config;
import com.media.publish.utils.EditSeekBar;
import com.media.publish.utils.LoadFrameTask;
import com.media.publish.utils.OnStickerOperateListener;
import com.media.publish.utils.StickerBottomView;
import com.media.publish.utils.StickerTextView;
import com.media.publish.utils.StickerViewGroup;
import com.media.publish.utils.TextBottomView;
import com.media.publish.utils.UtilsVideo;
import com.media.publish.utils.ViewOperator;
import com.media.publish.video_view.ListBottomView;
import com.media.publish.video_view.QNStickerBottomView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.qiniu.pili.droid.shortvideo.PLGifWatermarkSetting;
import com.qiniu.pili.droid.shortvideo.PLImageView;
import com.qiniu.pili.droid.shortvideo.PLMediaFile;
import com.qiniu.pili.droid.shortvideo.PLPaintView;
import com.qiniu.pili.droid.shortvideo.PLShortVideoEditor;
import com.qiniu.pili.droid.shortvideo.PLTextView;
import com.qiniu.pili.droid.shortvideo.PLVideoEditSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoFilterListener;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.xinlan.imageeditlibrary.editimage.utils.BaseUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.media.publish.utils.PaintBottomView;
import com.media.publish.utils.StickerImageViewTwo;

public class VideoEditActivity extends BaseActivity implements PLVideoSaveListener, PaintBottomView.OnPaintSelectorListener, View.OnClickListener{

    private static final String TAG = "VideoEditActivity";
    public static final String MP4_PATH = "MP4_PATH";
    public static final String MP4_PATH_MUSIC_NAME = "MP4_PATH_MUSIC_NAME";
    public static final String MP4_PATH_MUSIC_ID = "MP4_PATH_MUSIC_ID";
    private StickerImageViewTwo mStickerView;
    private QNStickerBottomView mQnStickerBottomView;
    private EditVideoAttributeBean mEditVideoAttributeBean;//记录特效信息
    private EditVideoAttributeBean mEditVideoAttrBean;//从裁剪界面过来，因为进入裁剪界面特效信息没有保存所以需要将数据再携带回来
    private ImageView mIvEditPopBack;
    private String mMp4pathMusicName = "";
    private String mMp4pathMusicId = "";
    private AudioManager mAudioManager;
    private EditSeekBar editVolume;
    private VolumeReceiver mVolumeReceiver;

    private enum PLShortVideoEditorStatus {
        IDLE,
        PLAYING,
        PAUSED,
    }

    private ViewOperator mViewOperator;
    private TextView mMusicHave;
    private FrameLayout mPreviewLayout, mRootView;
    private GLSurfaceView mPreviewView;
    private ImageView mPlayControlIv;
    private LinearLayout mLlBottomView;
    // 贴纸父控件
    private StickerViewGroup mStickerViewGroup;
    private FrameLayout mFlSticker;
    private Button nextBtn;
    private FrameLayout mTitleBar;

    private PaintBottomView mPaintBottomView;

    private PLShortVideoEditorStatus mShortVideoEditorStatus = PLShortVideoEditorStatus.IDLE;
    public static PLShortVideoEditor mShortVideoEditor;

    private String mMp4path;
    private boolean mIsPlaying = true;

    private PLMediaFile mMediaFile;
    private PLPaintView mPaintView;
    private ViewGroup.MarginLayoutParams mPaintViewLayoutParams;

    private LoadFrameTask mLoadFramesTask;
    private List<Bitmap> mVideoFrames = new ArrayList<>();

    private Point mScreenSize;

    private ListBottomView mFilterBottomView;
    private boolean mIsSelectingFilter;

    private TextBottomView mTextBottomView;
    private boolean mIsTextEffectEditing = false;
    private StickerTextView mCurTextView;
    private List<StickerTextView> mStickerTextViews;


    private LinearLayout mLlTieZhiBtn, mLlCaiJianBtn, mLlLvJingBtn, mLlTextBtn, mLlTuYaBtn, mLlMusicBtn;
    private Map<StickerImageViewTwo, PLGifWatermarkSetting> mGifViewSettings = new HashMap<>();
    private View mCurView;

    private View mAllView;
    //放音频路径
    private String mCurMusic = "";
    //
    private TextView mTextBack;

    private boolean isEdit = false;
    //是否通过eventbus 传值
    private boolean isPassEventbus;

    private Handler tHandler = new Handler();

    public static void start(Activity activity, String mp4Path, String mp4_path_music_id, String mp4_path_music_name, boolean isPassEventbus) {
        Intent intent = new Intent(activity, VideoEditActivity.class);
        intent.putExtra(MP4_PATH, mp4Path);
        intent.putExtra(MP4_PATH_MUSIC_ID, mp4_path_music_id);
        intent.putExtra(MP4_PATH_MUSIC_NAME, mp4_path_music_name);
        intent.putExtra("isPassEventbus", isPassEventbus);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_video_edit;
    }

    @Override
    protected void init() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        addActivity(this);
        //获取视频地址
        initGetIntent();
        //初始化View
        initView();
        //初始化视频等
        initData();
        //合成视频重要方法
        loadVideoThumbnails(mMediaFile, 20, 50, 50);

        //initGlSurfaceView();

        //点击事件或者滑动事件监听
        initOnClick();
        BaseUtils.checkInitImageLoader(VideoEditActivity.this);
    }

    private void initGetIntent() {
        mMp4path = getIntent().getStringExtra(MP4_PATH);
        if (getIntent().hasExtra("isEdit")) {
            isEdit = getIntent().getBooleanExtra("isEdit", false);
        }
        if (getIntent().hasExtra("isPassEventbus")) {
            isPassEventbus = getIntent().getBooleanExtra("isPassEventbus", false);
        }
        mMp4pathMusicName = getIntent().getStringExtra(MP4_PATH_MUSIC_NAME);
        mMp4pathMusicId = getIntent().getStringExtra(MP4_PATH_MUSIC_ID);
        mEditVideoAttrBean = (EditVideoAttributeBean) getIntent().getSerializableExtra("editVideoAttribute");
    }

    private void initView() {
        mScreenSize = UtilsVideo.getScreenSize(this);

        mRootView = findViewById(R.id.editor_layout);
        mRootView.setOnClickListener(this);

        //显示视频控件
        mPreviewView = findViewById(R.id.preview);
        //显示视频控件最外层
        mPreviewLayout = findViewById(R.id.preview_layout);
        //播放按钮
        mPlayControlIv = findViewById(R.id.play_control_iv);
        mIvEditPopBack = findViewById(R.id.iv_edit_pop_back);
        mIvEditPopBack.setOnClickListener(this);
        mTextBack = findViewById(R.id.back_btn);
        mTextBack.setOnClickListener(this);

        mMusicHave = findViewById(R.id.tv_music_have);
        mMusicHave.setOnClickListener(this);

        mPlayControlIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mShortVideoEditorStatus == PLShortVideoEditorStatus.PLAYING) {
                    pausePlayback();
                    mPlayControlIv.setVisibility(View.VISIBLE);
                } else {
                    startPlayback();
                    mPlayControlIv.setVisibility(View.GONE);
                }
            }
        });
        //工具栏 View
        mLlBottomView = findViewById(R.id.ll_bottom_view);
        //完成 关闭 View
        mTitleBar = findViewById(R.id.fl_title_bar);

        mStickerViewGroup = findViewById(R.id.sticker_container_view);
        mFlSticker = findViewById(R.id.fl_sticker);
        nextBtn = findViewById(R.id.next_btn);
        //贴纸编辑进度条

        mLlTieZhiBtn = findViewById(R.id.ll_tiezhi_btn);
        mLlTieZhiBtn.setOnClickListener(this);

        mLlCaiJianBtn = findViewById(R.id.ll_caijian_btn);
        mLlCaiJianBtn.setOnClickListener(this);

        mLlLvJingBtn = findViewById(R.id.ll_lvjing_btn);
        mLlLvJingBtn.setOnClickListener(this);

        mLlTextBtn = findViewById(R.id.ll_text_btn);
        mLlTextBtn.setOnClickListener(this);

        mLlTuYaBtn = findViewById(R.id.ll_tuya_btn);
        mLlTuYaBtn.setOnClickListener(this);

        mLlMusicBtn = findViewById(R.id.ll_music_btn);
        mLlMusicBtn.setOnClickListener(this);

        //动画初始化
        mViewOperator = new ViewOperator(mRootView, mTitleBar, mLlBottomView, mPreviewLayout);

        mFilterBottomView = new ListBottomView(this);

        if (isPassEventbus) {
            mLlTieZhiBtn.setVisibility(View.INVISIBLE);
            mLlLvJingBtn.setVisibility(View.INVISIBLE);
            mLlTextBtn.setVisibility(View.INVISIBLE);
        }
    }

    private void initData() {
        if (TextUtils.isEmpty(mMp4path)) return;
        //设置视频到控件上
        mMediaFile = new PLMediaFile(mMp4path);
        PLVideoEditSetting setting = new PLVideoEditSetting();
        setting.setSourceFilepath(mMp4path);
        setting.setDestFilepath(Config.VIDEO_STORAGE_DIR + System.currentTimeMillis() + ".mp4");
        setting.setGifPreviewEnabled(false);
        mShortVideoEditor = new PLShortVideoEditor(mPreviewView);
        mShortVideoEditor.setVideoEditSetting(setting);
        mShortVideoEditor.setVideoSaveListener(this);
        mShortVideoEditor.getDurationMs();

        mEditVideoAttributeBean = new EditVideoAttributeBean();

     /*   //添加水印
        PLWatermarkSetting mWatermarkSetting = new PLWatermarkSetting();
        mWatermarkSetting.setBitmap(BitmapUtils.INSTANCE.createView(this, "酣享@" + SpUtils.getInstance().getLoadUserBean().getData().getName()));
        mWatermarkSetting.setPosition(1f, 0.98f);
        mWatermarkSetting.setAlpha(128);
        mShortVideoEditor.setWatermark(mWatermarkSetting);
*/

        if (!TextUtils.isEmpty(mMp4pathMusicName)) {
            mMusicHave.setVisibility(View.VISIBLE);
            mMusicHave.setText("当前配乐：" + mMp4pathMusicName);
            mMusicHave.setSelected(true);
        }

        mVolumeReceiver = new VolumeReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.media.VOLUME_CHANGED_ACTION");
        this.registerReceiver(mVolumeReceiver, filter);
    }

    private void initGlSurfaceView() {
        //适配不同尺寸、涂鸦使用
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mPreviewLayout.getLayoutParams();
        FrameLayout.LayoutParams surfaceLayout = (FrameLayout.LayoutParams) mPreviewView.getLayoutParams();
        int outputWidth = mMediaFile.getVideoWidth();
        int outputHeight = mMediaFile.getVideoHeight();
        int rotation = mMediaFile.getVideoRotation();
        if ((rotation == 90 || rotation == 270)) {
            int temp = outputWidth;
            outputWidth = outputHeight;
            outputHeight = temp;
        }
        surfaceLayout.width = mScreenSize.x;
        surfaceLayout.height = Math.round((float) outputHeight * mScreenSize.x / outputWidth);
        ViewGroup.MarginLayoutParams marginParams = null;
        if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
            marginParams = surfaceLayout;
        } else {
            marginParams = new ViewGroup.MarginLayoutParams(surfaceLayout);
        }
        mPaintViewLayoutParams = marginParams;
        mPreviewLayout.setLayoutParams(layoutParams);
        mStickerViewGroup.setLayoutParams(marginParams);
        mPreviewView.setLayoutParams(marginParams);
    }

    private void initOnClick() {
        //贴纸编辑完成点击取消编辑状态
        mPreviewView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updatePlayStatus(!mIsPlaying);
                saveViewTimeAndHideRect();
                //隐藏贴纸组件
                if (mViewOperator != null) {
                    mViewOperator.hideBottomView();
                }
                mTitleBar.setVisibility(View.VISIBLE);
                mLlBottomView.setVisibility(View.VISIBLE);
                //隐藏边框
                widgetHide();
            }
        });
        setEchoVideoAttr();
    }

    /**
     * 添加图片贴纸
     */
    private void addImageView(Drawable drawable, String drawablePath) {
        mStickerView = (StickerImageViewTwo) View.inflate(VideoEditActivity.this, R.layout.sticker_image_view, null);
        mStickerView.setImageDrawable(drawable);
        mStickerView.setDrawablePath(drawablePath);
        mShortVideoEditor.addImageView(mStickerView);
        mStickerView.setOnStickerOperateListener(new StickerOperateListener(mStickerView));
        showViewBorder(mStickerView);

    }

    public void onClickSaveEdit(View v) {
        if (DoubleUtils.isFastDoubleClick()) return;
        updatePlayStatus(false);
        widgetHide();
        if (isPassEventbus) {
            //通过eventbus传值
            EventBusUtils.sendNotify1Value(MessageBus.msgId_select_img_video_path_list, mMp4path);
            return;
        }
        LoadingManager.showLoadingDialog(VideoEditActivity.this, "请稍后...");
        tHandler.postDelayed(() -> {
            if (LoadingManager.getLoadingDialog() != null)
                LoadingManager.getLoadingDialog().setCancelable(false);
        }, 500);
        mShortVideoEditor.save(new PLVideoFilterListener() {
            @Override
            public void onSurfaceCreated() {
            }

            @Override
            public void onSurfaceChanged(int i, int i1) {
            }

            @Override
            public void onSurfaceDestroy() {
                tHandler.postDelayed(() -> LoadingManager.hideLoadingDialog(VideoEditActivity.this), 500);
            }

            @Override
            public int onDrawFrame(int i, int i1, int i2, long l, float[] floats) {
                return i;
            }
        });
    }

    private void widgetHide() {
        //隐藏文字边框
        if (mCurTextView != null) {
            if (mStickerTextViews != null) {
                for (StickerTextView mStickerTextView : mStickerTextViews) {
                    mStickerTextView.setEditable(false);
                }
            }
            mCurTextView.setEditable(false);
        }
        //贴纸隐藏边框
        if (mStickerView != null) {
            mStickerView.setSelected(false);
        }
        if (mIsSelectingFilter) {
            mViewOperator.hideBottomView();
            mIsSelectingFilter = false;
            leftTopBtn();
        }
    }

    /**
     * 开始预览
     */
    private void startPlayback() {
        try {
            if (mShortVideoEditorStatus == PLShortVideoEditorStatus.IDLE) {
                mShortVideoEditor.startPlayback();
                mShortVideoEditorStatus = PLShortVideoEditorStatus.PLAYING;
            } else if (mShortVideoEditorStatus == PLShortVideoEditorStatus.PAUSED) {
                mShortVideoEditor.resumePlayback();
                mShortVideoEditorStatus = PLShortVideoEditorStatus.PLAYING;
            }
            mShortVideoEditorStatus = PLShortVideoEditorStatus.PLAYING;
        } catch (Exception e) {
            e.getMessage();
        }
    }

    /**
     * 暂停预览
     */
    private void pausePlayback() {
        if (mShortVideoEditor != null) {
            mShortVideoEditor.pausePlayback();
        }
        mShortVideoEditorStatus = PLShortVideoEditorStatus.PAUSED;
    }

    /**
     * 加载视频帧数据
     *
     * @param mediaFile   视频媒体文件
     * @param frameCount  帧数
     * @param frameWidth  缩略图的宽度
     * @param frameHeight 缩略图的高度
     */
    private void loadVideoThumbnails(final PLMediaFile mediaFile, int frameCount, int frameWidth, int frameHeight) {
        if (mLoadFramesTask == null && mVideoFrames.isEmpty()) {
            mLoadFramesTask = new LoadFrameTask(this, mediaFile, frameCount, frameWidth, frameHeight, new LoadFrameTask.OnLoadFrameListener() {
                @Override
                public void onFrameReady(Bitmap bitmap) {
                    if (bitmap != null) {
                        mVideoFrames.add(bitmap);
                        if (mIsTextEffectEditing) {
                            //mTextBottomView.addBitmap(bitmap);
                        }
                    }
                }
            });
            mLoadFramesTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    }

    private void setTextStickersSelectable(boolean selectable) {
        if (mStickerTextViews == null || mStickerTextViews.isEmpty()) {
            return;
        }
        for (StickerTextView stickerTextView : mStickerTextViews) {
            stickerTextView.setTextIsSelectable(selectable);
        }
    }


    private void updatePlayStatus(boolean isPlaying) {
        if (isPlaying) {
            startPlayback();
            mPlayControlIv.setVisibility(View.GONE);
            saveViewTimeAndHideRect();
        } else {
            pausePlayback();
            mPlayControlIv.setVisibility(View.VISIBLE);
            saveViewTimeAndHideRect();
        }
        mIsPlaying = isPlaying;
    }

    /**
     * 显示编辑框并为其添加初始时间
     */
    private void showViewBorder(View view) {
        mCurView = view;
        mCurView.setSelected(true);
        //pausePlayback();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back_btn) {
            closeAct();
        } else if (id == R.id.ll_tiezhi_btn) {
            showStickerView();
            mTitleBar.setVisibility(View.GONE);
            mLlBottomView.setVisibility(View.GONE);
        } else if (id == R.id.ll_caijian_btn) {
            setViewInfo();
            Intent caijian = new Intent(VideoEditActivity.this, VideoTrimActivity.class);
            caijian.putExtra(MP4_PATH_MUSIC_NAME, mMp4pathMusicName);
            caijian.putExtra(MP4_PATH_MUSIC_ID, mMp4pathMusicId);
            caijian.putExtra(VideoTrimActivity.VIDEO_PATH, mMp4path);
            caijian.putExtra(VideoTrimActivity.VIDEO_PATH_OLD, mMp4path);
            caijian.putExtra("isPassEventbus", isPassEventbus);
            if (mEditVideoAttributeBean != null) {
                caijian.putExtra("editVideoAttribute", mEditVideoAttributeBean);
            }
            startActivity(caijian);
            finish();
        } else if (id == R.id.ll_lvjing_btn) {
            FilterItemAdapter filterItemAdapter = new FilterItemAdapter(this, new ArrayList<>(Arrays.asList(mShortVideoEditor.getBuiltinFilterList())), new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.built_in_filters))));
            filterItemAdapter.setOnFilterSelectListener(new FilterItemAdapter.OnFilterSelectListener() {
                @Override
                public void onFilterSelected(String filterName, String description) {
                    mShortVideoEditor.setBuiltinFilter(filterName);
                    mEditVideoAttributeBean.setFilterAttr(filterName);
                }
            });
            mFilterBottomView.init(filterItemAdapter, 4);
            mViewOperator.showBottomView(mFilterBottomView);
            mIsSelectingFilter = true;
            leftTopBtn();
        } else if (id == R.id.ll_text_btn) {
            upDataCreateText();
            mIsSelectingFilter = true;
        } else if (id == R.id.iv_edit_pop_back) {
            mViewOperator.hideBottomView();
            mIsSelectingFilter = false;
            leftTopBtn();
        } else if (id == R.id.ll_tuya_btn) {
            if (mPaintView == null) {
                mPaintView = new PLPaintView(this, mPreviewView.getWidth(), mPreviewView.getHeight());
                mPaintView.setLayoutParams(mPaintViewLayoutParams);
                mShortVideoEditor.addPaintView(mPaintView);
            }
            if (mPaintBottomView == null) {
                mPaintBottomView = new PaintBottomView(this);
                mPaintBottomView.setOnPaintSelectorListener(this);
            }
            mPaintView.setPaintEnable(true);
            mViewOperator.showBottomView(mPaintBottomView);
        }
        if (mIsTextEffectEditing) {
            if (mStickerTextViews != null) {
                for (StickerTextView mStickerTextView : mStickerTextViews) {
                    mStickerTextView.setEditable(false);
                }
            }
            mTextBottomView.startPlayer();
        }
    }

    private void closeAct() {
        DialogManager.showConfirmDialog(VideoEditActivity.this, "", "是否放弃当前编辑的内容？", "放弃", "取消", new DialogManager.Listener() {
            @Override
            public void onItemLeft() {
                finish();
            }

            @Override
            public void onItemRight() {

            }
        });
    }

    private void leftTopBtn() {
        mTextBack.setVisibility(mIsSelectingFilter ? View.GONE : View.VISIBLE);
        mIvEditPopBack.setVisibility(mIsSelectingFilter ? View.VISIBLE : View.GONE);
    }

    private void setViewInfo() {
        //文字特效
        if (mCurTextView != null && mEditVideoAttributeBean != null) {
            mEditVideoAttributeBean.setVideoAddTextAttr(new EditVideoAttributeBean.StickerTextViewBean(
                    mCurTextView.getRect().left, mCurTextView.getRect().right, mCurTextView.getRect().top, mCurTextView.getRect().bottom,
                    mCurTextView.getText().toString(), mCurTextView.getCurrentTextColor(), mCurTextView.getTextSize(), mCurTextView.getDegree(), mCurTextView.getScale(), mPreviewView.getHeight()));
        }
        //贴纸特效
        if (mStickerView != null && mEditVideoAttributeBean != null) {
            mEditVideoAttributeBean.setVideoStickerAttr(new EditVideoAttributeBean.StickerImageViewTwoBean(mStickerView.getFinalLeft(), mStickerView.getFinalRight(), mStickerView.getFinalTop(), mStickerView.getFinalBottom(),
                    mStickerView.getImageDegree(), mStickerView.getImageScale(), mStickerView.getDrawablePath()));
        }
    }

    private void upDataCreateText() {
        if (mTextBottomView == null) {
            mTextBottomView = new TextBottomView(this, this, mMediaFile, getLayoutInflater());
            mTextBottomView.setOnViewOperateListener(new StickerBottomView.OnViewOperateListener() {
                @Override
                public void onConfirmClicked() {
                    mViewOperator.hideBottomView();
                    if (mCurTextView != null && mCurTextView.isEditable()) {
                        mCurTextView.setEditable(false);
                    }
                    mIsTextEffectEditing = false;
                    //setTextStickersSelectable(false);
                }

                @Override
                public void onPlayStatusPaused() {
                    updatePlayStatus(false);
                }

                @Override
                public void onPlayProgressChanged(int position) {
                    mShortVideoEditor.seekTo(position);
                }

                @Override
                public void onCloseBottomView() {
                    KeyBoardUtils.hideShowKeyboard(VideoEditActivity.this);
                    mViewOperator.hideBottomView();
                }
            });
            mTextBottomView.setOnTextSelectorListener(new TextBottomView.OnTextSelectorListener() {
                @Override
                public void onTextAdded(StickerTextView textView, long startTimeMs, long durationMs) {
                    if (mStickerTextViews == null) {
                        mStickerTextViews = new ArrayList<>();
                    }
                    if (mCurTextView != null && mCurTextView.isEditable()) {
                        mCurTextView.setEditable(false);
                    }
                    mCurTextView = textView;
                    mStickerTextViews.add(textView);
                    mShortVideoEditor.addTextView(textView);
                    mTextBottomView.setProceedStickerTextViews(mStickerTextViews);
                    mShortVideoEditor.setViewTimeline(textView, 0, mMediaFile.getDurationMs());
                    KeyBoardUtils.hideShowKeyboard(VideoEditActivity.this);
                }

                @Override
                public void onTextSelected(StickerTextView textView) {
                    mCurTextView = textView;
                    mCurTextView.setEditable(true);
                }

                @Override
                public boolean onTextEdited(StickerTextView mStickerText) {
                    if (mStickerTextViews.contains(mStickerText)) {
                        mStickerTextViews.get(mStickerTextViews.indexOf(mStickerText));
                    }
                    mTextBottomView.setEditText(mStickerText.getText().toString());
                    mTextBottomView.setProceedStickerTextView(mCurTextView);
                    mViewOperator.showBottomView(mTextBottomView);
                    return true;
                }

                @Override
                public boolean onTextDeleted() {
                    mShortVideoEditor.removeTextView(mCurTextView);
                    mStickerTextViews.remove(mCurTextView);
                    if (mCurTextView != null) {
                        mCurTextView = null;
                    }
                    return true;
                }

                @Override
                public void onTextRangeChanged(StickerTextView textView, long startTimeMs, long durationMs) {
                    KeyBoardUtils.hideShowKeyboard(VideoEditActivity.this);
                }
            });
        }
        mViewOperator.showBottomView(mTextBottomView);
        //用于控制 回复初始化时的状态数据
        mTextBottomView.setEditText("");
        mTextBottomView.showSoftInputFromWindow(this);
        mTextBottomView.initStateView();
        mTextBottomView.setProceedStickerTextView(null);
        mTextBottomView.keyboardListener(this);
        //用于控制 回复初始化时的状态数据

        mIsTextEffectEditing = true;
        mShortVideoEditor.seekTo(0);
//        setTextStickersSelectable(true);
    }


    /**
     * 底部贴纸View
     */
    private void showStickerView() {
        if (mQnStickerBottomView == null) {
            mQnStickerBottomView = new QNStickerBottomView(this);
            mQnStickerBottomView.setOnImageSelectedListener((drawable, assetsPath) -> {
                if (drawable != null) {
                    mViewOperator.hideBottomView();

                    addImageView(drawable, assetsPath);
                }
            });
        }
        mViewOperator.showBottomView(mQnStickerBottomView);
        mIsSelectingFilter = true;
        leftTopBtn();
    }

    /**
     * 贴图操作监听
     */
    private class StickerOperateListener implements OnStickerOperateListener {
        private View mView;

        StickerOperateListener(View view) {
            mView = view;
        }

        /**
         * 当点击删除贴图
         */
        @Override
        public void onDeleteClicked() {
            if (mView instanceof StickerTextView) {
                mShortVideoEditor.removeTextView((PLTextView) mView);
            } else {
                if (((StickerImageViewTwo) mView).getGifPath() != null) {
                    if (mStickerViewGroup != null) {
                        mStickerViewGroup.removeView(mView);
                    }
                    mShortVideoEditor.removeGifWatermark(mGifViewSettings.get(mView));
                    mGifViewSettings.remove(mView);

                } else {
                    mShortVideoEditor.removeImageView((PLImageView) mView);
                }
                mStickerView = null;
            }
            mCurView = null;
        }

        /**
         * 当点击贴图编辑
         */
        @Override
        public void onEditClicked() {
        }

        @Override
        public void onRotateClicked() {

        }

        /**
         * 当贴图被选中
         */
        @Override
        public void onStickerSelected() {
            if (mView instanceof StickerImageViewTwo) {
                mView.setSelected(true);
            }

        }
    }

    /**
     * 保存当前 View 的时间调整并隐藏编辑框
     */
    private void saveViewTimeAndHideRect() {
        if (mCurView != null) {
            View rectView = (View) mCurView.getTag(R.id.selector_view);
            mCurView.setTag(R.id.rect_view, rectView);
            mShortVideoEditor.setViewTimeline(mCurView, 0, mMediaFile.getDurationMs());
            mCurView.setSelected(false);
            mCurView = null;
        }
    }

    /**
     * 更新贴纸状态
     */
    private void saveGifSetting() {
        if (mCurView != null && mCurView instanceof StickerImageViewTwo && ((StickerImageViewTwo) mCurView).getGifPath() != null) {
            StickerImageViewTwo stickerImageView = (StickerImageViewTwo) mCurView;
            PLGifWatermarkSetting gifWatermarkSetting = mGifViewSettings.get(stickerImageView);
            gifWatermarkSetting.setDisplayPeriod(stickerImageView.getStartTime(), stickerImageView.getEndTime() - stickerImageView.getStartTime());
            gifWatermarkSetting.setPosition((float) stickerImageView.getViewX() / mFlSticker.getWidth(), (float) stickerImageView.getViewY() / mFlSticker.getHeight());
            gifWatermarkSetting.setRotation((int) stickerImageView.getImageDegree());
            gifWatermarkSetting.setAlpha(255);
            gifWatermarkSetting.setSize(stickerImageView.getImageWidth() * stickerImageView.getImageScale() / mStickerViewGroup.getWidth(), stickerImageView.getImageHeight() * stickerImageView.getImageScale() / mStickerViewGroup.getHeight());
            mShortVideoEditor.updateGifWatermark(gifWatermarkSetting);
        }
    }

    @Override
    public void onSaveVideoSuccess(String filePath) {
        Intent intent = new Intent(this, ReleaseDynamicActivity.class);
        intent.putExtra("Dynamictype", 2);
        if (filePath.equals(mMp4path) && isEdit) {
            String appPath = StorageUtils.getAppPath(StorageUtils.SAVE_MP4_PATH);
            String newPath = appPath + "/" + System.currentTimeMillis() + ".mp4";

            LoadingManager.showLoadingDialog(VideoEditActivity.this, "请稍后...");
            tHandler.postDelayed(() -> {
                if (LoadingManager.getLoadingDialog() != null)
                    LoadingManager.getLoadingDialog().setCancelable(false);
            }, 500);
            FileUtils.copyVideoFile(mMp4path, new FileUtils.OnCopyFileListener() {
                @Override
                public void onCopyOver(String filePath) {
                    tHandler.postDelayed(() -> {
                        LoadingManager.hideLoadingDialog(VideoEditActivity.this);
                        intent.putExtra(ReleaseDynamicViewModel.QINIUVIDEO_TIME, mMediaFile.getDurationMs());
                        intent.putExtra(ReleaseDynamicViewModel.QINIUVCOVER_PATH, "");
                        intent.putExtra(MP4_PATH, newPath);
                        startActivity(intent);
                    }, 500);
                }
                @Override
                public void onCopyError() {
                    tHandler.postDelayed(() -> {
                        LoadingManager.hideLoadingDialog(VideoEditActivity.this);
                        ToastUtils.showShort(getApplicationContext(), "视频保存失败");
                    }, 500);
                }
            });
        } else {

            LoadingManager.hideLoadingDialog(VideoEditActivity.this);
            intent.putExtra(ReleaseDynamicViewModel.QINIUVIDEO_TIME, mMediaFile.getDurationMs());
            intent.putExtra(ReleaseDynamicViewModel.QINIUVCOVER_PATH, "");
            intent.putExtra(MP4_PATH, filePath);
            nextBtn.setEnabled(true);
            startActivity(intent);
        }
    }

    @Override
    public void onSaveVideoFailed(final int errorCode) {
        runOnUiThread(() -> {
            tHandler.postDelayed(() -> LoadingManager.hideLoadingDialog(VideoEditActivity.this), 500);
            ToastUtils.showShort(this,"视频保存失败");
        });
    }

    @Override
    public void onSaveVideoCanceled() {
        runOnUiThread(() -> {
            tHandler.postDelayed(() -> LoadingManager.hideLoadingDialog(VideoEditActivity.this), 500);
            ToastUtils.showShort(this,"视频保存取消");
        });
    }

    @Override
    public void onProgressUpdate(final float percentage) {
    }

    @Override
    public void onPaintColorSelected(int color) {
        mPaintView.setPaintColor(color);
    }

    @Override
    public void onPaintSizeSelected(int size) {
        mPaintView.setPaintSize(size);
    }

    @Override
    public void onPaintUndoSelected() {
        mPaintView.undo();
    }

    @Override
    public void onPaintClearSelected() {
        mPaintView.clear();
    }

    @Override
    public void onViewClosed() {
        mPaintView.setPaintEnable(false);
        mViewOperator.hideBottomView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 103:
                break;
            default:
                break;
        }
    }

    private void setEchoVideoAttr() {
        if (mEditVideoAttrBean != null) {
            if (mEditVideoAttrBean.getVideoStickerAttr() != null) {
                setEchoViewInfo(3);
            }
            if (mEditVideoAttrBean.getFilterAttr() != null) {
                setEchoViewInfo(1);
            }
            if (mEditVideoAttrBean.getVideoAddTextAttr() != null) {
                setEchoViewInfo(2);
            }
        }
    }

    public void setEchoViewInfo(int viewType) {
        if (mShortVideoEditor == null)
            return;
        switch (viewType) {
            case 1://滤镜
                mShortVideoEditor.setBuiltinFilter(mEditVideoAttrBean.getFilterAttr());
                mEditVideoAttributeBean.setFilterAttr(mEditVideoAttrBean.getFilterAttr());
                break;
            case 2://文字
                EditVideoAttributeBean.StickerTextViewBean videoAddText = mEditVideoAttrBean.getVideoAddTextAttr();
                mCurTextView = new StickerTextView(this);
                mPreviewView.post(() -> {
                    mCurTextView.showEdit(false);
                    mCurTextView.setEditable(true);
                    mCurTextView.setRect(new Rect(videoAddText.left, videoAddText.top, videoAddText.right, videoAddText.bottom));
                    mCurTextView.setDegree(videoAddText.rotate);
                    mCurTextView.setScale(videoAddText.scale);
                    mCurTextView.setTextColor(videoAddText.color);
                    mCurTextView.setText(videoAddText.content);
                    mCurTextView.setTextSize(videoAddText.textSize);
                    mShortVideoEditor.addTextView(mCurTextView);
                    mCurTextView.setIsLocation(false);
                    //记录信息

                    EditVideoAttributeBean.StickerTextViewBean mStickerTextViewBean = new EditVideoAttributeBean.StickerTextViewBean(videoAddText.left, videoAddText.right, videoAddText.top, videoAddText.bottom,
                            videoAddText.content, videoAddText.color, videoAddText.textSize, videoAddText.rotate, videoAddText.scale, videoAddText.viewHeight);
                    mEditVideoAttributeBean.setVideoAddTextAttr(mStickerTextViewBean);

                    mCurTextView.setOnStickerOperateListener(new OnStickerOperateListener() {
                        @Override
                        public void onDeleteClicked() {
                            mShortVideoEditor.removeTextView(mCurTextView);
                            mStickerTextViews.remove(mCurTextView);
                            if (mCurTextView != null) {
                                mCurTextView = null;
                            }
                        }

                        @Override
                        public void onEditClicked() {

                        }

                        @Override
                        public void onRotateClicked() {

                        }

                        @Override
                        public void onStickerSelected() {
                        }
                    });
                    if (mStickerTextViews == null) {
                        mStickerTextViews = new ArrayList<>();
                    }
                    mStickerTextViews.add(mCurTextView);
                });
                break;
            case 3://贴纸
                ImageView imageView = new ImageView(this);
                EditVideoAttributeBean.StickerImageViewTwoBean videoStickerAttr = mEditVideoAttrBean.getVideoStickerAttr();
                ImageLoader.getInstance().displayImage(videoStickerAttr.drawablePath, imageView);
                mStickerView = new StickerImageViewTwo(this);
                mPreviewView.post(() -> {
                    mStickerView.setSelected(false);
                    mStickerView.setTouchable(true);
                    mStickerView.setImageDrawable(imageView.getDrawable());
                    mStickerView.setLocation(videoStickerAttr.left, videoStickerAttr.top, videoStickerAttr.right, videoStickerAttr.bottom);
                    mStickerView.setImageDegree(videoStickerAttr.rotate);
                    mStickerView.setImageScale(videoStickerAttr.scale);
                    mShortVideoEditor.addImageView(mStickerView);
                    mStickerView.setIsLocation(false);
                    mStickerView.setOnStickerOperateListener(new StickerOperateListener(mStickerView));
                    showViewBorder(mStickerView);

                    EditVideoAttributeBean.StickerImageViewTwoBean mStickerImageViewTwoBean = new EditVideoAttributeBean.StickerImageViewTwoBean(videoStickerAttr.left, videoStickerAttr.right, videoStickerAttr.bottom, videoStickerAttr.top,
                            videoStickerAttr.rotate, videoStickerAttr.scale, videoStickerAttr.drawablePath);
                    mEditVideoAttributeBean.setVideoStickerAttr(mStickerImageViewTwoBean);
                });
                break;
            case 4://音乐
                break;
        }
    }

    private class VolumeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")) {
                if (mAudioManager != null && editVolume != null) {
                    int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    editVolume.setProgress(currentVolume);
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (mIsSelectingFilter) {
            mViewOperator.hideBottomView();
            mIsSelectingFilter = false;
            leftTopBtn();
        } else {
            closeAct();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        updatePlayStatus(true);
        startPlayback();
    }

    @Override
    protected void onPause() {
        super.onPause();
        updatePlayStatus(false);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoadFramesTask != null && mLoadFramesTask.getStatus() == AsyncTask.Status.RUNNING) {
            mLoadFramesTask.cancel(true);
            mLoadFramesTask = null;
        }
        if (mVolumeReceiver != null)
            unregisterReceiver(mVolumeReceiver);
    }

}
